<template>
  <fill-height-scroll-view @scroll="getScroll">
    <view slot="element">
      <!-- 顶部导航 start -->
      <view class="f-x-bt bf p03">
        <scroll-view v-if="sarr.length" class='ws-n sarr pt10 bf' scroll-x='true'>
          <block v-for="(v,i) in sarr" :key='i'>
            <view @click="clickSarr(i)" class='f-g-0 mr15 bs10 c6 dis-in sarri f28 t-c'
              :class="{wei:v.active}"
              :style="{
                background: v.active ? ' #FE9367' : '', 
                color: v.active ? '#fff' : '#000'
              }">
              {{ v.name }}
            </view>
          </block>
        </scroll-view>
        <!-- <view class="t-r" style="width: 200rpx;">
          <u-action-sheet :list="date" :visible.sync="showDate" @click="selectDate"></u-action-sheet>
          <view @click="showDate = true">{{dateTitle}}
            <text class="iconfont icondown wei c0 f24 ml5"></text>
          </view>
        </view> -->
      </view>
      <!-- 顶部导航 end -->

      <view class="p3 bf mt20">
        <view class="w100 f-bt">
          <view class="title f32">计费明细</view>
          <view class="c6" @click="goMoney">查看详情></view>
        </view>
        <view class="cardList">
          <view class="card" v-for="(item,index) in showList" :key="item.name" @click="choose(index)">
            <text class="f26">{{item.name}}</text>
            <text class="f34 mt20">{{item.num}}</text>
            <text class="ca2 f24">{{item.rateName}}<text class="cfa">{{item.rate}}</text></text>
          </view>
        </view>
        <view class="qiun-charts cell mt30">
          <qiun-data-charts canvasId="Paymix" :canvas2d="true" :inScrollView="true"
            :opts="{xAxis:{labelCount:5}}" type="mix" :chartData="LineData" background="#FFFFFF"
            :tooltipShow="false" @getIndex="getIndex" />
          <!-- tooltip start -->
          <view class="tooltip" v-if="showTooltip">
            <view>{{tooltopData.title}}</view>
            <view v-for="item in tooltopData.data" :key="item.name" class="f-s-c">
              <view :style="{background:item.color}"
                style="width: 26rpx;height: 26rpx;border-radius: 50%;margin-right: 10rpx;"></view>
              <text>{{item.name}}</text>
              <text>{{item.value}}</text>
            </view>
          </view>
          <!-- tooltip end-->
        </view>
      </view>
      <u-calendar v-model="showrl" mode="range" :btnstyle="{ background: '#FE9367' }" range-color="#FE9367"
        range-bg-color="rgba(253,215,75,0.2)" active-bg-color="#FE9367" @change="changeDate"></u-calendar>
    </view> <!-- 闭合 slot="element" 的 view -->
  </fill-height-scroll-view>
</template>

<script>
	import {
		utilMixins
	} from "@/common/util-mixins.js"
	import qiunDataCharts from '@/yb_shd/dp/components/qiun-data-charts/qiun-data-charts.vue'
	import FillHeightScrollView from '@/yb_shd/dp/components/fill-height-scroll-view.vue'

	// 日期格式化方法
	const formatDate = (date, fmt = 'YYYY-MM-DD') => {
		const pad = n => n.toString().padStart(2, '0')
		return fmt
			.replace('YYYY', date.getFullYear())
			.replace('MM', pad(date.getMonth() + 1))
			.replace('DD', pad(date.getDate()))
	}

	export default {
		components: {
			qiunDataCharts,
			FillHeightScrollView
		},
		mixins: [utilMixins],
		data() {
			return {
				showTooltip: false,
				tooltopData: {},
				showrl: false,
				showDate: false,
				dateType: 1, // 1:今日 2:昨日
				pageScrollTop: 0,
				LineData: null,
				query: {
					timeType: 1,
					startTime: '',
					endTime: ''
				},
				totalList: {
					todayList: [{
							name: '配送订单',
							num: 0,
							rateName: '完成率：',
							rate: '0%'
						},
						{
							name: '扣减费用',
							num: 0,
							rateName: '费率：',
							rate: '0%'
						}
					],
					yesterdayList: [{
							name: '配送订单',
							num: 0,
							rateName: '完成率：',
							rate: '0%'
						},
						{
							name: '扣减费用',
							num: 0,
							rateName: '费率：',
							rate: '0%'
						}
					]
				},
				date: [{
						text: '今日',
						value: 1
					},
					{
						text: '近七日',
						value: 2
					},
					{
						text: '近十五日',
						value: 3
					},
					{
						text: '具体时间',
						value: 4
					}
				],
				dateTitle: '今日',
				chartData: {
					todayData: {
						series: [{
							data: [{
									name: '配送订单',
									value: 0
								},
								{
									name: '扣减费用',
									value: 0
								}
							]
						}]
					},
					yesterdayData: {
						series: [{
							data: [{
									name: '配送订单',
									value: 0
								},
								{
									name: '扣减费用',
									value: 0
								}
							]
						}]
					}
				},
				sarr: [{
						name: '今日',
						active: true,
						type: 1
					},
					{
						name: '昨日',
						active: false,
						type: 2
					}
				],
			}
		},
		computed: {
			showData() {
				return this.dateType === 1 ?
					this.chartData.todayData :
					this.chartData.yesterdayData
			},
			showList() {
				return this.dateType === 1 ?
					this.totalList.todayList :
					this.totalList.yesterdayList
			}
		},
		created() {
			this.fetchData()
		},
		methods: {
			async fetchData() {
				try {
					// 生成模拟数据
					const generateMock = () => ({
						orderCount: Math.floor(Math.random() * 100 + 50),
						feeAmount: Math.floor(Math.random() * 5000 + 2000),
						completeRate: (Math.random() * 20 + 80).toFixed(1) + '%',
						feeRate: (Math.random() * 5 + 2).toFixed(1) + '%'
					})

					// 获取当前日期
					const getDateParams = () => {
						const date = new Date()
						if (this.dateType === 2) date.setDate(date.getDate() - 1)
						return {
							date: formatDate(date)
						}
					}

					// 更新列表数据
					const updateListData = (data, key) => {
						this.totalList[key][0].num = data.orderCount
						this.totalList[key][0].rate = data.completeRate
						this.totalList[key][1].num = data.feeAmount
						this.totalList[key][1].rate = data.feeRate
					}

					// 主逻辑
					const params = getDateParams()
					const mockData = generateMock()
					const listKey = this.dateType === 1 ? 'todayList' : 'yesterdayList'

					updateListData(mockData, listKey)
					this.getChartData(mockData)

				} catch (e) {
					this.util.message(e.msg, 3)
				}
			},

			getChartData(data) {
				// 更新饼图数据
				const chartKey = this.dateType === 1 ? 'todayData' : 'yesterdayData'
				this.chartData[chartKey].series[0].data = [{
						name: '配送订单',
						value: data.orderCount
					},
					{
						name: '扣减费用',
						value: data.feeAmount
					}
				]

				// 生成折线图数据（24小时）
				this.LineData = {
					categories: Array.from({
						length: 24
					}, (_, i) => `${i}:00`),
					series: [{
							name: "配送订单",
							data: Array.from({
								length: 24
							}, () => Math.floor(Math.random() * 50 + 20)),
							color: '#36c87a',
							type: "line",
							style: "curve"
						},
						{
							name: "配送费用",
							data: Array.from({
								length: 24
							}, () => Math.floor(Math.random() * 3000 + 500)),
							color: ' #FE9367',
							type: "line",
							style: "curve"
						}
					]
				}
			},

			// 日期范围变更
			changeDate(e) {
				this.query.startTime = e.startDate
				this.query.endTime = e.endDate
				this.fetchData()
			},

			// 日期类型选择
			selectDate(index) {
				const option = this.date[index]
				this.dateTitle = option.text
				this.query.timeType = option.value
				option.value === 4 ? (this.showrl = true) : this.fetchData()
			},

			// 切换今日/昨日
			clickSarr(index) {
				this.sarr.forEach((item, i) => {
					item.active = i === index
					if (i === index) {
						this.dateType = item.type
						this.fetchData()
					}
				})
			},

			// 保持其他方法不变
			getIndex(e) {
				if (this.showTooltip || e.currentIndex.index === -1) return

				const tooltipData = {
					title: e.currentIndex.categories,
					data: [{
							color: '#36c87a',
							name: '配送订单',
							value: this.LineData.series[0].data[e.currentIndex.index]
						},
						{
							color: ' #FE9367',
							name: '配送费用',
							value: '￥' + this.LineData.series[1].data[e.currentIndex.index].toFixed(2)
						}
					]
				}

				this.tooltopData = tooltipData
				this.showTooltip = true
				setTimeout(() => this.showTooltip = false, 2000)
			},

			getScroll(e) {
				this.pageScrollTop = e.detail.scrollTop
			},
			
			goMoney(){
				uni.navigateTo({
					url:'/yb_shd/dp/muddle/muddle_money'
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	.title {
		position: relative;
		margin-left: 20rpx;
		font-weight: bold;
		color: #000;
	}

	.title::after {
		content: "";
		position: absolute;
		width: 10rpx;
		height: 20rpx;
		left: -20rpx;
		top: 50%;
		transform: translateY(-50%);
		background: #FE9367;
	}

	.cardList {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
		font-size: 30rpx;

		.card {
			display: flex;
			flex-direction: column;
			width: 48%;
			height: 160rpx;
			background: #FFFFFF;
			border: 1px solid #ccc;
			margin-top: 20rpx;
			border-radius: 10rpx;
			justify-content: center;
			padding: 20rpx;
		}

		.card-inactive {
			display: flex;
			flex-direction: column;
			width: 220rpx;
			height: 160rpx;
			background: #FFFFFF;
			border: 1px solid #ccc;
			margin-top: 20rpx;
			border-radius: 10rpx;
			justify-content: center;
			padding: 20rpx;
		}

		.card-active {
			display: flex;
			flex-direction: column;
			width: 220rpx;
			height: 160rpx;
			background: #FEFAED;
			margin-top: 20rpx;
			border: 1px solid #E3BD76;
			border-radius: 10rpx;
			justify-content: center;
			padding: 20rpx;
			font-weight: bold;
		}
	}

	.analysis {
		display: flex;
		flex-direction: column;
		width: 220rpx;
		height: 160rpx;
		margin-top: 20rpx;
		justify-content: center;
	}

	.qiun-charts {
		width: 730rpx;
		height: 500rpx;
		background-color: #FFFFFF;
		margin-left: -40rpx;
	}

	.charts-ring {
		margin: 0 auto;
		width: 600rpx;
		height: 350rpx;
		background-color: #FFFFFF;
	}

	.tooltip {
		position: absolute;
		left: 50%;
		top: 40%;
		transform: translate(-50%, -50%);
		width: 400rpx;
		padding: 20rpx 30rpx;
		border-radius: 20rpx;
		background-color: rgba(0, 0, 0, .9);
		color: #FFFFFF;
	}
</style>